package com.yaxin.system.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.yaxin.common.utils.StringUtils;
import com.yaxin.flowable.common.constant.ProcessConstants;
import com.yaxin.flowable.common.enums.ProcessStatus;
import com.yaxin.flowable.core.FormConf;
import com.yaxin.workflow.service.IWfProcessService;
import com.yaxin.workflow.service.IWfTaskService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * Flowable 全局监听器
 *
 * @author konbai
 * @since 2023/3/8 22:45
 */
@Component
@Slf4j
public class GlobalEventListener extends AbstractFlowableEngineEventListener implements ExecutionListener{

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private  IWfProcessService processService;

    private  IWfTaskService wfTaskService;

    /**
     * 流程结束监听器
     */
    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        String processInstanceId = event.getProcessInstanceId();
        Object variable = runtimeService.getVariable(processInstanceId, ProcessConstants.PROCESS_STATUS_KEY);
        ProcessStatus status = ProcessStatus.getProcessStatus(Convert.toStr(variable));
        if (ObjectUtil.isNotNull(status) && ProcessStatus.RUNNING == status) {
            runtimeService.setVariable(processInstanceId, ProcessConstants.PROCESS_STATUS_KEY, ProcessStatus.COMPLETED.getStatus());
        }
        super.processCompleted(event);
    }

    @Override
    public void notify(DelegateExecution delegateExecution) {
        System.out.println("流程实例ID: " + wfTaskService);
        // ============ 新增：更新业务表单状态 ============
        // 获取业务主键（推荐用 businessKey 存放表单ID）
        String definitionId = delegateExecution.getProcessDefinitionId();
        String processInstanceId = delegateExecution.getProcessInstanceId();
        // 查询 ProcessInstance 对象
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
            .processInstanceId(processInstanceId)
            .singleResult();
        String deployedId = processInstance.getDeploymentId();
//        String businessKey = delegateExecution.getProcessInstanceBusinessKey();
        FormConf formConf = processService.selectFormContent(definitionId, deployedId, processInstanceId);
        if (formConf != null) {
            List<Map<String, Object>> fields = formConf.getFields();
            // 修改表单状态，比如 "已完成"
            //formService.updateStatus(formId, FormStatus.COMPLETED);
            log.info("流程 {} 结束，更新表单 {} 状态为 COMPLETED", delegateExecution.getProcessInstanceId() , fields.toString());
        }
    }
}
